<template>
  <div class="app-container">
    <el-form ref="elForm" :disabled="$route.query.isInfo" :model="formData" :rules="rules" size="medium"
      label-width="120px">
      <h2 style="text-align: center"></h2>
      <h4 class="form-header h4">基本信息</h4>
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="受控编号" prop="fileCode">
            <el-input v-model="formData.fileCode" placeholder="请输入受控编号" clearable :style="{ width: '100%' }">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文件关键字" prop="keyword">
            <el-input v-model="formData.keyword" placeholder="请输入文件关键字" clearable :style="{ width: '100%' }">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文件名称" prop="fileName">
            <el-input v-model="formData.fileName" placeholder="请输入文件名称" clearable :style="{ width: '100%' }">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文件类型" prop="fileTypeValue">
            <el-select v-model="formData.fileTypeValue" placeholder="请选择文件类型" clearable :style="{ width: '100%' }" @change="changefileTypeValue">
              <el-option v-for="dict in dict.type.sys_file_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.fileTypeValue == 3">
          <el-form-item label="发文类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择文件状态" clearable
              :style="{ width: '100%' }">
              <el-option  label="其他" :value="0" />
              <el-option  label="任命" :value="1" />
              <el-option  label="授权" :value="2" />

            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="所属项目" prop="projectId">
            <el-select
              :style="{ width: '100%' }"
              v-model="formData.projectId"
              filterable
              placeholder="请选择所属项目"
            >
              <el-option
                v-for="dict in projectList"
                :key="dict.projectId"
                :label="dict.projectName"
                :value="dict.projectId"
              />
            </el-select>
          </el-form-item>
        </el-col> -->

        <el-col :span="8">
          <el-form-item label="文件状态" prop="fileStatusValue">
            <el-select multiple ref="fileStatus" v-model="formData.fileStatusValue" placeholder="请选择文件状态" clearable
              :style="{ width: '100%' }">
              <el-option v-for="dict in dict.type.sys_file_status" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="文件废止日期" prop="endDate">
            <el-date-picker v-model="formData.endDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              :style="{ width: '100%' }" placeholder="请选择文件废止日期" clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文件实施日期" prop="startDate">
            <el-date-picker v-model="formData.startDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              :style="{ width: '100%' }" placeholder="请选择文件实施日期" clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" >
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" clearable :style="{ width: '100%' }">
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8" v-if="formData.fileTypeValue==3">
          <el-form-item label="是否显示" prop="isShow">
            <el-switch v-model="formData.isShow">
            </el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.fileTypeValue==3">
          <el-form-item label="是否置顶" prop="isRecommend">
            <el-switch v-model="formData.isRecommend">
            </el-switch>
          </el-form-item>
        </el-col> -->
      </el-row>
      <h4 class="form-header h4">附件信息</h4>
      <el-form-item label="" prop="fileUrl">
        <FileUpload :isDelete="!$route.query.isInfo" v-model="formData.fileUrl"></FileUpload>
      </el-form-item>
      <el-form-item label="关联个人" prop="isRel">
        <el-radio-group v-model="formData.isRel">
          <el-radio label="0">否</el-radio>
          <el-radio label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="formData.isRel == 1" label="员工姓名" prop="redDocVos">
        <!-- <el-tag :key="index" v-for="(item, index) in nextUser" closable :disable-transitions="false"
          @close="handleClose('next', item)">
          {{ item.nickName }}
        </el-tag> -->
        <!-- <el-button class="button-new-tag" type="primary" icon="el-icon-plus" size="mini" circle
          @click="onSelectNextUsers" /> -->
          <UserDialogSelection :disabled="$route.query.isInfo || isInfo" @change="changeOpen($event, scope.$index)"
                placeholder="请选择内审组成员" v-model="formData.redDocVos"></UserDialogSelection>
      </el-form-item>

      <el-col :span="24">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!$route.query.isInfo" type="primary" @click="submitForm">提交</el-button>
          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
    <el-dialog :title="userData.title" :visible.sync="userData.open" width="60%" append-to-body>
      <el-row type="flex" :gutter="20">
        <!--部门数据-->
        <el-col :span="5">
          <el-card shadow="never" style="height: 100%">
            <div slot="header">
              <span>部门列表</span>
            </div>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search" />
              <el-tree :data="deptOptions" :props="deptProps" :expand-on-click-node="false"
                :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" />
            </div>
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-table ref="userTable" :key="userData.type" height="500" v-loading="userLoading" :data="userList"
            highlight-current-row @current-change="changeCurrentUser" @selection-change="handleSelectionChange">
            <el-table-column v-if="userData.type === 'copy' || userData.type === 'next'" width="55" type="selection" />
            <el-table-column v-else width="30">
              <template slot-scope="scope">
                <el-radio :label="scope.row.userId" v-model="currentUserId">{{
                  ""
                }}</el-radio>
              </template>
            </el-table-column>
            <el-table-column label="用户名" align="center" prop="nickName" />
            <el-table-column label="手机" align="center" prop="phonenumber" />
            <el-table-column label="部门" align="center" prop="dept.deptName" />
          </el-table>
          <pagination :total="total" :page-sizes="[200]" :page.sync="queryParams1.pageNum" :limit.sync="queryParams1.pageSize"
            @pagination="getListUser" />
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userData.open = false">取 消</el-button>
        <el-button type="primary" @click="submitUserData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fileManagerAdd,
  updategFileManager,
  fileManagerInfo,
} from "@/api/system/fileManager.js";
import { listSelect } from "@/api/business/project.js";
import { selectUser, deptTreeSelect } from "@/api/system/user";

export default {
  components: {},
  dicts: ["sys_file_type", "sys_file_status"],

  props: [],
  data() {
    return {
      total:0,
      userList: [],
      deptName: "",
      deptProps: {
        children: "children",
        label: "label",
      },
      userData: {
        title: "",
        type: "",
        open: false,
      },
      deptOptions: [],
      userLoading: false,
      queryParams1: {
        deptId: undefined,
        // pageNum: 1,
        // pageSize: 10,
      },
      nextUser: [],
      userMultipleSelection: [],

      projectList: [],
      formData: {
        isRel: "0",
        projectId: undefined,
        fileCode: undefined,
        userId: undefined,
        fileTypeValue: undefined,
        fileName: undefined,
        fileStatusValue: [],
        isApplyValue: undefined,
        endDate: null,
        startDate: null,
        keyword: "",
        isShow:0,
        isRecommend:0,
        type:0
      },
      rules: {
        // projectId: [
        //   {
        //     required: true,
        //     message: "请输入所属项目",
        //     trigger: "blur",
        //   },
        // ],
        fileCode: [
          {
            required: true,
            message: "请输入受控编号",
            trigger: "blur",
          },
        ],
        // keyword: [
        //   {
        //     required: false,
        //     message: "请输入关键字",
        //     trigger: "change",
        //   },
        // ],
        // fileTypeValue: [
        //   {
        //     required: true,
        //     message: "请选择文件类型",
        //     trigger: "change",
        //   },
        // ],
        // fileUrl: [
        //   {
        //     required: true,
        //     message: "附件不能为空",
        //     trigger: "change",
        //   },
        // ],
        // fileName: [
        //   {
        //     required: true,
        //     message: "请输入文件名称",
        //     trigger: "blur",
        //   },
        // ],
        // fileStatusValue: [
        //   {
        //     required: true,
        //     message: "请选择文件状态",
        //     trigger: "change",
        //   },
        // ],
        // type:[
        // {
        //     required: true,
        //     message: "请选择发文类型",
        //     trigger: "change",
        //   },
        // ],
        // endDate: [
        //   {
        //     required: false,
        //     message: "请选择文件废止日期",
        //     trigger: "change",
        //   },
        // ],
        // startDate: [
        //   {
        //     required: true,
        //     message: "请选择文件实施日期",
        //     trigger: "change",
        //   },
        // ],
      },
    };
  },
  computed: {},
  watch: {},
  created() {
    this.listSelect();
    if (this.$route.query.isEdit || this.$route.query.isInfo) {
      this.getinfo();
    }
  },
  mounted() { },
  methods: {
    listSelect() {
      listSelect().then((response) => {
        this.projectList = response.data;
      });
    },
    changefileTypeValue(e){
      console.log(e);
    },
    getinfo() {
      fileManagerInfo(this.$route.query.id).then((response) => {
        this.formData = response.data;
        this.formData.fileStatusValue =
          this.formData.fileStatusValue.split(",");
        if (this.formData.redDocVos) {
          let u = this.formData.redDocVos.map((item) => {
            return {
              nickName: item.nickName,
              userId: item.isRelUserId,
            };
          });
          this.nextUser = u;
          this.userMultipleSelection = this.nextUser;
        } else {
          this.nextUser = [];
          this.userMultipleSelection = this.nextUser;
        }
      });
    },

    submitForm() {
      console.log(this.formData.isRel,this.formData.redDocVos);
      if (this.formData.isRel == 1 && this.formData.redDocVos.length==0) {
        this.$modal.msgWarning("请选择关联员工");
        return;
      } 
      else if (this.formData.isRel == 1 && this.formData.redDocVos.length != 0) {
        this.formData.redDocVos = this.formData.redDocVos.map((item) => {
          return { isRelUserId: item };
        });
      }
      console.log(this.formData.redDocVos);
      // this.formData.redDocVos = this.formData.redDocVos.toString()
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          let query = JSON.parse(JSON.stringify(this.formData));
          query.fileStatusLabel = this.$refs.fileStatus.selected
            .map((e) => e.label)
            .toString();
          query.fileTypeLabel = this.dict.type.sys_file_type.find(
            (i) => i.value === query.fileTypeValue
          ).label;
          query.fileStatusValue = query.fileStatusValue.toString();
          if (this.formData.fileManagerId != undefined) {
            updategFileManager(query).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            fileManagerAdd(query).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        }
      });
    },
    resetForm() {
      const obj = { path: "./file" };
      this.$tab.closeOpenPage(obj);
    },
    /** 查询用户列表 */
    getListUser() {
      this.userLoading = true;
      selectUser(this.addDateRange(this.queryParams1, this.dateRange)).then(
        (response) => {
          this.userList=response.rows;
          this.total = response.total;
          this.toggleSelection(this.userMultipleSelection);

          console.log(this.userList);
          this.userLoading = false;
        }
      );
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams1.deptId = data.id;
      this.getListUser();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection);
      this.userMultipleSelection = selection;
      
    },
    changeCurrentUser(val) {
      this.currentUserId = val.userId;
    },
    toggleSelection(selection) {
      console.log(selection);
      console.log(this.userList);
      if (selection && selection.length > 0) {
        this.$nextTick(() => {
          selection.forEach((item) => {
            let row = this.userList.find((k) => k.userId === item.userId);
            console.log("row", row);

            this.$refs.userTable.toggleRowSelection(row);
          });
        });
      } else {
        this.$nextTick(() => {
          this.$refs.userTable.clearSelection();
        });
      }
    },
    submitUserData() {
      let type = this.userData.type;
      if (
        !this.userMultipleSelection ||
        this.userMultipleSelection.length <= 0
      ) {
        this.$modal.msgError("请选择用户");
        return false;
      }
      let userIds = this.userMultipleSelection.map((k) => k.userId);
      this.nextUser = this.userMultipleSelection;
      this.userData.open = false;
    },
    onSelectNextUsers() {
      this.userMultipleSelection = this.nextUser;
      this.onSelectUsers("关联员工", "next");
    },
    onSelectUsers(title, type) {
      this.userData.title = title;
      this.userData.type = type;
      this.getTreeSelect();
      this.getListUser();
      this.userData.open = true;
    },
    // 关闭标签
    handleClose(type, tag) {
      let userObj = this.userMultipleSelection.find(
        (item) => item.userId == tag.userId
      );
      this.userMultipleSelection.splice(
        this.userMultipleSelection.indexOf(userObj),
        1
      );
      this.nextUser = this.userMultipleSelection;
    },
    getTreeSelect() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
  },
};
</script>
<style scoped lang="scss">
.button-new-tag {
  margin-left: 10px;
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>
